#include "iapserver.h"
#include "iapsession.h"
#include "clientservercommon.h"

#include <QMessageBox>
#include <mw/eikappui.h>
#include <mw/apgtask.h>
#include <mw/APGWGNAM.H>
#include <e32cmn.h>

#include <QDebug>

CIAPServer::CIAPServer():
    CServer2(EPriorityNormal)
{
}

CIAPServer::~CIAPServer()
{
    delete iFocusObserver;
}

CIAPServer* CIAPServer::NewLC()
{
    CIAPServer* self = new(ELeave) CIAPServer();
    CleanupStack::PushL(self);
    self->ConstructL();
    return self;
}

void CIAPServer::ConstructL()
{
    RSemaphore semaphore;
    User::LeaveIfError(semaphore.OpenGlobal(KIAPServerSemaphoreName));

    StartL(KIAPServerName);

    //hide application from tasklist
    //http://www.developer.nokia.com/Community/Wiki/TSS000044_-_Hiding_an_application_from_the_task_list
    iSelfWinID = CCoeEnv::Static()->RootWin().Identifier();
    RWsSession session = CCoeEnv::Static()->WsSession();
    CApaWindowGroupName* wgName = CApaWindowGroupName::NewLC(session, iSelfWinID);
    wgName->SetHidden(ETrue);
    wgName->SetWindowGroupName(CCoeEnv::Static()->RootWin());
    CleanupStack::PopAndDestroy();

    // Signal to client the server is ready
    semaphore.Signal();
    semaphore.Close();

    // find host application
    TApaTaskList taskList(CCoeEnv::Static()->WsSession());
    TApaTask task = taskList.FindByPos(0); /// 0 for hidden task, 1 for visible
    iHostWinID = task.WgId();
    iFocusObserver = CGainFocusEventObserver::NewL(*this, iHostWinID);
}

CSession2* CIAPServer::NewSessionL(const TVersion&, const RMessage2& aMsg) const
{
    return CIAPSession::NewL(iHostWinID, iSelfWinID);
}

void CIAPServer::Notify(TInt event)
{
    CIAPSession* session;

    iSessionIter.SetToFirst();
    while((session = static_cast<CIAPSession*>(iSessionIter++)) != NULL){
        session->ClientAppFocusChanged(event);
    };
}


